/**********************************************************************
Replication file for:

Gillooly, Shauna N. and Jamie L. Shenk.
"Formalizing Corporate Counterinsurgency: State–Company Security Contracts 
in Colombia's Extractive Industries"
Latin American Research Review

This do-file reproduces all quantitative results in the article.
**********************************************************************/

version 17
clear all
set more off
set maxvar 32767
set matsize 11000

* Set random seed for reproducibility
set seed 123456


/**********************************************************************
Directory structure
**********************************************************************/
* This do-file assumes it is run from the top-level replication folder

global ROOT "."

* Data
global CLEAN   "$ROOT/Data/Clean"

* Outputs
global LOGS    "$ROOT/Logs"

cap mkdir "$LOGS"

* Log file
log using "$LOGS/replication.log", replace text


/**********************************************************************
PANEL DATA ANALYSIS
**********************************************************************/
use "$CLEAN/Gillooly_Shenk_CCdata.dta", clear
xtset codmpio ano


/**********************************************************************
Main models (Table 1)
**********************************************************************/
**threats**
xtpoisson o_amenazas convenio coca regalias i.ano, vce(robust) fe  

**detentions**
xtpoisson num_arrests convenio regalias coca i.ano, vce(robust) fe 

**social leader assasinations**
preserve
keep if ano > 2015
xtpoisson socialleaderkilled convenio coca regalias i.ano, vce(robust) fe  
restore

**homicidios*
xtpoisson homicidios convenio coca regalias i.ano, vce(robust) fe 

**armed confrontations*
xtpoisson cont_arm convenio coca regalias i.ano, vce(robust) fe  

/**********************************************************************
Main models (Table 2)
**********************************************************************/

**threats**
xtpoisson o_amenazas convenio oil coca regalias i.ano, vce(robust) fe  
xtpoisson o_amenazas convenio metals coca regalias i.ano, vce(robust) fe 

**detentionss**
xtpoisson num_arrests convenio oil regalias coca i.ano, vce(robust) fe  
xtpoisson num_arrests convenio metals regalias coca i.ano, vce(robust) fe

**social leader assasinations**
preserve
keep if ano > 2015
xtpoisson socialleaderkilled convenio oil coca regalias i.ano, vce(robust) fe  
xtpoisson socialleaderkilled convenio metals coca regalias i.ano, vce(robust) fe
restore

**homicidios*
xtpoisson homicidios convenio oil coca regalias i.ano, vce(robust) fe
xtpoisson homicidios convenio metals coca regalias i.ano, vce(robust) fe  

**armed confrontations*
xtpoisson cont_arm convenio oil coca regalias i.ano, vce(robust) fe  
xtpoisson cont_arm convenio metals coca regalias i.ano, vce(robust) fe  


clear

/**********************************************************************
Appendix analyses and robustness checks
**********************************************************************/
use "$CLEAN/Gillooly_Shenk_CCdata.dta", clear
xtset codmpio ano


* Counts and basics
quietly count
local N_all = r(N)

quietly levelsof codmpio, local(munis)
local n_munis : word count `munis'

quietly summarize ano
local ymin = r(min)
local ymax = r(max)
local years_span = "`ymin'–`ymax'"

quietly summarize convenio
local share_treat = r(mean)
local share_treat_pct = 100*`share_treat'

quietly count if convenio==1 & oil==1
local N_oil = r(N)
quietly count if convenio==1 & metals==1
local N_met = r(N)

* Write to Excel
putexcel set "appendix_descriptives.xlsx", sheet("A2.1 Coverage") replace
putexcel A1=("Item") B1=("Value"), bold
putexcel A2=("Municipality-years")              B2=(`N_all')
putexcel A3=("Municipalities")                  B3=(`n_munis')
putexcel A4=("Years")                           B4=("`years_span'")
putexcel A5=("% muni-years with convenio")      B5=(`share_treat_pct')
putexcel A6=("# treated muni-years with oil")   B6=(`N_oil')
putexcel A7=("# treated muni-years with metals") B7=(`N_met')

*a.2.2**
set more off

preserve
    * 1) Ensure one row per municipality–year
    sort ano codmpio
    by ano codmpio: keep if _n==1

    * 2) Flags
    gen byte any_cc   = convenio==1
    gen byte oil_cc   = convenio==1 & oil==1
    gen byte metal_cc = convenio==1 & metals==1

    * 3) Denominator: # municipalities observed in each year
    bys ano: gen byte _tag = _n==1
    bys ano: egen muni_total = total(_tag)
    drop _tag

    * 4) Collapse to year-level counts
    collapse (sum) any_cc oil_cc metal_cc (max) muni_total, by(ano)
    order ano muni_total any_cc oil_cc metal_cc

    * 5) Shares (optional but handy)
    gen share_any   = any_cc   / muni_total
    gen share_oil   = oil_cc   / muni_total
    gen share_metal = metal_cc / muni_total
    format share_* %6.3f

    * 6) Export
    export excel using "appendix_descriptives.xlsx", ///
        sheet("A2.2 By year") firstrow(variables) sheetreplace
restore
* A2.3
version 18
set more off

* 0) Auto-detect treatment variable (edit list if needed)
local treat_candidates "convenio convenio_dummy convenio_plus lconvenio"
local TREAT ""
foreach t in `treat_candidates' {
    capture confirm variable `t'
    if !_rc {
        local TREAT "`t'"
        continue, break
    }
}
if "`TREAT'"=="" {
    di as error "No treatment variable found among: `treat_candidates'. Aborting A2.3."
    exit 111
}
di as txt "A2.3 using treatment variable: " as result "`TREAT'"

* 1) Choose variables (keep only those that exist AND are numeric)
local outcomes_all "o_amenazas socialleaderkilled num_arrests homicidios cont_arm"
local covars_all   "coca regalias"

local allvars ""
foreach v in `outcomes_all' `covars_all' {
    capture confirm variable `v'
    if !_rc {
        capture confirm numeric variable `v'
        if !_rc local allvars `allvars' `v'
        else di as error "Note: variable `v' exists but is non-numeric — skipping."
    }
    else di as error "Note: variable `v' not found — skipping."
}
if "`allvars'"=="" {
    di as error "No requested numeric variables found; aborting A2.3."
    exit 459
}
di as txt "A2.3 will summarize: " as result "`allvars'"

* -------------------- (1) OVERALL --------------------
tempfile desc_overall
postutil clear
tempname p1
postfile `p1' str30 varname double mean sd p25 p50 p75 max using `desc_overall', replace
foreach v of local allvars {
    quietly summarize `v', detail
    post `p1' ("`v'") (r(mean)) (r(sd)) (r(p25)) (r(p50)) (r(p75)) (r(max))
}
postclose `p1'

preserve
    use `desc_overall', clear
    export excel using "appendix_descriptives.xlsx", ///
        sheet("A2.3 Overall") firstrow(variables) sheetreplace
restore

* -------------------- (2) BY TREATMENT + StdDiff --------------------
tempfile desc_by
postutil clear
tempname p2
postfile `p2' str30 varname double ///
    mean0 sd0 N0 mean1 sd1 N1 using `desc_by', replace

foreach v of local allvars {
    quietly count if `TREAT'==0
    local N0 = r(N)
    quietly count if `TREAT'==1
    local N1 = r(N)

    quietly summarize `v' if `TREAT'==0
    local m0 = r(mean)
    local s0 = r(sd)

    quietly summarize `v' if `TREAT'==1
    local m1 = r(mean)
    local s1 = r(sd)

    post `p2' ("`v'") (`m0') (`s0') (`N0') (`m1') (`s1') (`N1')
}
postclose `p2'

preserve
    use `desc_by', clear
    gen stddiff = (mean1-mean0) / sqrt((sd0^2 + sd1^2)/2)
    format stddiff %6.3f
    order varname mean0 sd0 N0 mean1 sd1 N1 stddiff
    export excel using "appendix_descriptives.xlsx", ///
        sheet("A2.3 ByTreat") firstrow(variables) sheetreplace

    keep varname stddiff
    export excel using "appendix_descriptives.xlsx", ///
        sheet("A2.3 StdDiff") firstrow(variables) sheetreplace
restore

* A2.4: Descriptives within treated muni-years by sector ----------
version 18
set more off

* 0) auto-detect treatment variable (edit the list if needed)
local treat_candidates "convenio convenio_dummy convenio_plus lconvenio"
local TREAT ""
foreach t in `treat_candidates' {
    capture confirm variable `t'
    if !_rc {
        local TREAT "`t'"
        continue, break
    }
}
if "`TREAT'"=="" {
    di as error "No treatment variable found among: `treat_candidates'. Aborting A2.4."
    exit 111
}
di as txt "A2.4 using treatment variable: " as result "`TREAT'"

* 1) make sure sector flags exist
capture confirm variable oil
if _rc {
    di as error "Variable 'oil' not found."; exit 111
}
capture confirm variable metals
if _rc {
    di as error "Variable 'metals' not found."; exit 111
}

* 2) variables to summarize (keep only existing + numeric)
local want "o_amenazas socialleaderkilled num_arrests homicidios cont_arm coca regalias"
local ylist ""
foreach v in `want' {
    capture confirm variable `v'
    if !_rc {
        capture confirm numeric variable `v'
        if !_rc local ylist `ylist' `v'
        else di as error "Note: `v' exists but is non-numeric — skipping."
    }
    else di as error "Note: `v' not found — skipping."
}
if "`ylist'"=="" {
    di as error "No numeric variables to summarize; aborting A2.4."
    exit 459
}
di as txt "A2.4 will summarize: " as result "`ylist'"

* 3) compute stats within treated muni-years by sector
tempfile a24
postutil clear
tempname P
postfile `P' str32 varname double ///
    mean_o sd_o N_o ///
    mean_m sd_m N_m ///
    mean_b sd_b N_b using `a24', replace

preserve
    * ensure one row per muni-year (defensive)
    capture confirm variable codmpio
    if !_rc {
        capture confirm variable ano
        if !_rc {
            sort ano codmpio
            by ano codmpio: keep if _n==1
        }
    }

    keep if `TREAT'==1
    gen byte both = oil==1 & metals==1

    foreach v of local ylist {
        quietly count if oil==1
        local N_o = r(N)
        quietly summarize `v' if oil==1
        local mo = r(mean)
        local so = r(sd)

        quietly count if metals==1
        local N_m = r(N)
        quietly summarize `v' if metals==1
        local mm = r(mean)
        local sm = r(sd)

        quietly count if both==1
        local N_b = r(N)
        quietly summarize `v' if both==1
        local mb = r(mean)
        local sb = r(sd)

        post `P' ("`v'") (`mo') (`so') (`N_o') ///
                       (`mm') (`sm') (`N_m') ///
                       (`mb') (`sb') (`N_b')
    }
restore
postclose `P'

* 4) export to the SAME Excel workbook, new tab
preserve
    use `a24', clear
    order varname mean_o sd_o N_o mean_m sd_m N_m mean_b sd_b N_b
    export excel using "appendix_descriptives.xlsx", ///
        sheet("A2.4 Sectors") firstrow(variables) sheetreplace
restore


*****************ROBUTSNESS***********************
//panel but with restricted time period//
preserve
keep if ano < 2011
xtpoisson o_amenazas convenio oil regalias i.ano, vce(robust) fe  
xtpoisson num_arrests convenio oil regalias i.ano, vce(robust) fe  
xtpoisson homicidios convenio oil regalias i.ano, vce(robust) fe  
xtpoisson cont_arm convenio oil regalias i.ano, vce(robust) fe  

xtpoisson o_amenazas convenio metals regalias i.ano, vce(robust) fe
xtpoisson num_arrests convenio metals regalias i.ano, vce(robust) fe
xtpoisson homicidios convenio metals regalias i.ano, vce(robust) fe
xtpoisson cont_arm convenio metals regalias i.ano, vce(robust) fe

restore

**lags**
xtpoisson o_amenazas L.convenio L.oil coca regalias i.ano, vce(robust) fe  
xtpoisson o_amenazas L.convenio L.metals coca regalias i.ano, vce(robust) fe 

xtpoisson num_arrests L.convenio L.oil regalias coca i.ano, vce(robust) fe
xtpoisson num_arrests L.convenio L.metals regalias coca i.ano, vce(robust) fe

preserve
keep if ano > 2015
xtpoisson socialleaderkilled L.convenio L.metals coca regalias i.ano, vce(robust) fe
xtpoisson socialleaderkilled L.convenio L.oil coca regalias i.ano, vce(robust) fe  
restore

xtpoisson homicidios L.convenio L.oil coca regalias i.ano, vce(robust) fe  
xtpoisson homicidios L.convenio L.metals coca regalias i.ano, vce(robust) fe

xtpoisson cont_arm L.convenio L.oil coca regalias i.ano, vce(robust) fe  
xtpoisson cont_arm L.convenio L.metals coca regalias i.ano, vce(robust) fe

//panel but with restricted time period//
preserve
keep if ano < 2011
xtpoisson o_amenazas convenio oil regalias i.ano, vce(robust) fe  
xtpoisson num_arrests convenio oil regalias i.ano, vce(robust) fe  
xtpoisson homicidios convenio oil regalias i.ano, vce(robust) fe  
xtpoisson cont_arm convenio oil regalias i.ano, vce(robust) fe  

xtpoisson o_amenazas convenio metals regalias i.ano, vce(robust) fe
xtpoisson num_arrests convenio metals regalias i.ano, vce(robust) fe
xtpoisson homicidios convenio metals regalias i.ano, vce(robust) fe
xtpoisson cont_arm convenio metals regalias i.ano, vce(robust) fe


restore
clear
log close
